package com.lingkang.sales.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.lingkang.sales.data.vo.MenuVo;
import java.util.ArrayList;
import java.util.List;

public class MenuUtil {

  public static void main(String[] args) {
    List<MenuVo> list = new ArrayList<>();
    list.add(new MenuVo(1, 0, "江苏省级", "url", "icon", 1));
    list.add(new MenuVo(2, 1, "江苏南京", "url", "icon", 2));
    list.add(new MenuVo(3, 2, "南京城北", "url", "icon", 3));
    list.add(new MenuVo(4, 1, "江苏淮安", "url", "icon", 4));
    list.add(new MenuVo(5, 3, "南京城北-分部AA", "url", "icon", 5));
    list.add(new MenuVo(6, 3, "南京城北-分部BB", "url", "icon", 6));
    List<MenuVo> tree = listToTree(list, 0);
    System.out.println(JSONObject.toJSON(tree));
  }


  public static List<MenuVo> listToTree(List<MenuVo> data, int parentId) {
    List<MenuVo> childrens = new ArrayList<>();
    for (MenuVo vo : data) {
      if (vo.getParentId() == parentId) {
        childrens.add(vo);
      }
    }
    findChildren(childrens, data);
    return childrens;
  }

  private static void findChildren(List<MenuVo> childrens, List<MenuVo> list) {
    for (MenuVo v : childrens) {
      List<MenuVo> children = new ArrayList<>();
      for (MenuVo dept : list) {
        if (v.getId() != null && v.getId() == dept.getParentId()) {
          children.add(dept);
        }
      }
      v.setChildren(children);
      findChildren(children, list);
    }
  }
}
